<?php

namespace app\admin\controller\withdraw;

use app\common\controller\Backend;
use app\common\library\Openapi;
use app\common\model\User;
use fast\Http;
use fast\Random;
use think\Db;
use think\Env;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 提现记录
 *
 * @icon fa fa-circle-o
 */
class UserWithdraw extends Backend
{

    /**
     * UserWithdraw模型对象
     * @var \app\admin\model\withdraw\UserWithdraw
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\withdraw\UserWithdraw;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
	
	/**
	 * 查看
	 *
	 * @return string|Json
	 * @throws \think\Exception
	 * @throws DbException
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags', 'trim']);
		if (false === $this->request->isAjax()) {
			return $this->view->fetch();
		}
		//如果发送的来源是 Selectpage，则转发到 Selectpage
		if ($this->request->request('keyField')) {
			return $this->selectpage();
		}
		[$where, $sort, $order, $offset, $limit] = $this->buildparams();

		$list = $this->model
			->with(['user'])
			->where($where)
			->order($sort, $order)
			->paginate($limit);
        $ret = Openapi::requestPost('/api/merchant/getBalance');
        $ret = json_decode($ret);
        if ($ret->code != 0){
           $this->error($ret->msg);
        }
        $data = Openapi::desDecrypt($ret->data);
        $data = json_decode($data);
        $amount = 0;
        $availableAmount = 0;
        foreach ($data as $item){
            if($item->payBankType == 'CMB'){
                $amount = $item->amount;
                $availableAmount = $item->availableAmount;
            }
        }
		$result = ['total' => $list->total(), 'rows' => $list->items(),"extend" => [
            'amount' => $amount,
            'availableAmount' => $availableAmount
        ]];
		return json($result);
	}
	
	
	/**
	 * 编辑
	 *
	 * @param $ids
	 * @return string
	 * @throws DbException
	 * @throws \think\Exception
	 */
	public function edit($ids = null)
	{
		$row = $this->model->get($ids);
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
			$this->error(__('You have no permission'));
		}
		if (false === $this->request->isPost()) {
			
			if ($row->status == 1){
				$this->view->assign("statusList", ['1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3')]);
			}else{
				$this->view->assign("statusList", [$row->status => __("Status $row->status")]);
			}
			$this->view->assign('row', $row);
			return $this->view->fetch();
		}
		$params = $this->request->post('row/a');
		if (empty($params)) {
			$this->error(__('Parameter %s can not be empty', ''));
		}
		$params = $this->preExcludeFields($params);
		$result = false;
		Db::startTrans();
		try {
			//是否采用模型验证
			if ($this->modelValidate) {
				$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
				$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
				$row->validateFailException()->validate($validate);
			}
			
			if ($params['status'] ==2&&$row->status == 1){
				//进行打款操作
				$data = [
					'requestId' => $row->order_sn,
					'name'=>Openapi::aesEncrypt($row->type == 1?$row->name:$row->ali_name),
					'idNumber'=>  Openapi::aesEncrypt($row->idcard),
					'salaryType'=>$row->type==1?0:1,
					'bankType'=>Openapi::aesEncrypt($row->type==1?'CMB':'ALIPAY'),
					'account'=>Openapi::aesEncrypt($row->type==1?$row->account:$row->ali_account),
					'amount'=>Openapi::aesEncrypt($row->real_amount),
					'callbackUrl'=> Openapi::aesEncrypt($this->request->domain().'/api/Notify/withdrawNotify'),
					'mobile'=>Openapi::aesEncrypt($row->type==1?$row->mobile:$row->ali_mobile),
				];
				
				$ret = Openapi::requestPost('/api/order/doWithdraw',$data);
				$ret = json_decode($ret);
				if ($ret->code != 0){
					throw new Exception($ret->msg);
				}
			}
			if ($params['status'] ==3&&$row->status == 1){
				//驳回 退回余额
				User::money($row->amount,$row->user_id,'提现驳回：'.$params['reason']);
			}
			$result = $row->allowField(true)->save($params);
			Db::commit();
		} catch (ValidateException|PDOException|Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		if (false === $result) {
			$this->error(__('No rows were updated'));
		}
		$this->success();
	}


}
